﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.IO;
using System.Web;
using System.Diagnostics;
using WindowsFormsApplication1.Properties;
using System.Net;
using System.Collections.Specialized;
using System.Xml;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.Xml;

namespace WindowsFormsApplication1
{
    public partial class Check : Form
    {
        public string signatur;
        public string filename = null;
        XmlDocument x;  
        static String dig = "http://www.w3.org/2000/09/xmldsig#";
        String sl = "http://www.buergerkarte.at/namespaces/securitylayer/1.2#";


        public Check setFile(String fn) {
            setfilename(fn);
            using (FileStream fs = new FileStream(filename, FileMode.Open))
            {
                using (StreamReader r = new StreamReader(fs, Encoding.UTF8))
                {
                    this.setSig(r.ReadToEnd());
                }
            }           
            return this;
        }

        public Check setfilename(string fn){
            filename=fn;           
            this.Text=filename;
            return this;       
        }

        
        public Check setSig(String sig) {
            x=new XmlDocument();
            x.PreserveWhitespace = true;    
            x.LoadXml(sig);
          
            signatur = sig;
            textBox2.Text = sig;

            if (x.GetElementsByTagName("ErrorResponse", sl).Count > 0) 
            {
                MessageBox.Show(                   
                    x.GetElementsByTagName("Info", sl)[0].InnerText,
                    x.GetElementsByTagName("ErrorCode", sl)[0].InnerText
                    );
                return this;
            }
            if (x.GetElementsByTagName("CreateXMLSignatureResponse", sl).Count > 0||                 
                x.GetElementsByTagName("VerifyXMLSignatureRequest", sl).Count > 0
                )
            {
                this.Show();
                textBox1.Text = "CMS..";
                textBox1.Text += " " +VerifyXml(sig);
                foreach(XmlNode a in x.GetElementsByTagName("Object", dig)){
                    textBox1.Text += "\r\n****\r\n" + a.InnerText;
                   
                }   
            }
            if (x.GetElementsByTagName("CreateCMSSignatureResponse", sl).Count > 0 ||
                x.GetElementsByTagName("VerifyCMSSignatureRequest", sl).Count > 0
              )
            {
                this.Show();
                textBox1.Text = "CMS..";
                String cms=x.GetElementsByTagName("CMSSignature", sl)[0].InnerText;
                textBox1.Text = cms;

                SignedCms signedCms = new SignedCms();           
                signedCms.Decode(System.Convert.FromBase64String(cms) );

                //

                textBox1.Text = "CMS" +signedCms.SignerInfos[0].Certificate.Subject;
                textBox1.Text+= new System.Text.ASCIIEncoding().GetString(signedCms.ContentInfo.Content);
                signedCms.CheckSignature(false); 
            } 
            this.Show();            
            return this;
        }

        public Check()
        {
            InitializeComponent();       
        }


        private void Check_Load(object sender, EventArgs e)
        {
            h.hTextbox(textBox1).ReadOnly=true;
            h.hTextbox(textBox2).ReadOnly=true;
            h.hTool(toolStrip1, "Speichern").Click += (s, s1) =>
            {
                saveFileDialog1.ShowDialog();
            };
            h.hTool(toolStrip1, "an bürgerkarte.at").Click += (s, s1) =>
            {
                string tempFile = Path.GetTempFileName()+".html";
             
                using (FileStream fs = new FileStream(tempFile, FileMode.OpenOrCreate))
                {
                    using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
                    {
                        HttpUtility.HtmlAttributeEncode(signatur);
                        w.Write(signatur);
                        w.Close();
                        
                    }
                }
                Process.Start(tempFile);

                CookieContainer cookies = new CookieContainer();
                //add or use cookies

                System.Collections.Specialized.NameValueCollection querystring = new NameValueCollection();
                querystring["uname"] = "uname";
                querystring["passwd"] = "snake3";
                string uploadfile;// set to file to upload

                uploadfile = "c:\\test.jpg";

                //everything except upload file and url can be left blank if needed

                string outdata = h.UploadFileEx(uploadfile,
                     "http://localhost/test.php", "uploadfile", "image/pjpeg", querystring, cookies);


                

                //File.Delete(tempFile);
            };
            h.hTool(toolStrip1, "an lokale BKU").Click += (s, s1) =>
            {
                HTTPC h1 = new HTTPC();
                h1.seteCallback((d) =>
                {
                    HTTPC.Procedure1 x = new HTTPC.Procedure1(() =>
                    {
                        new Check().setSig(d);
                    });
                    if (this.InvokeRequired) this.Invoke(x); else x();
                });
                h1.pruefenXML(textBox1.Text.Trim());
            };

            h.hTool(toolStrip1, "an lokale BKU").Click += (s, s1) =>
            {
                HTTPC h1 = new HTTPC();
                h1.seteCallback((d) =>
                {
                    HTTPC.Procedure1 x = new HTTPC.Procedure1(() =>
                    {
                        new Check().setSig(d);
                    });
                    if (this.InvokeRequired) this.Invoke(x); else x();
                });
                h1.pruefenXML(textBox1.Text.Trim());
            };





        }

        public static Boolean VerifyXml(String s)
        {         
            XmlDocument xmlDocument = new XmlDocument();       
            xmlDocument.PreserveWhitespace = true;      
            xmlDocument.LoadXml(s);
          //  MessageBox.Show(s);
          //  SignedXml signedXml = new SignedXml(xmlDocument);
         //   
            XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature", dig);
            
           
           // SignedXml signedXml = new SignedXml();
            SignedXml signedXml = new SignedXml((XmlElement)nodeList[0]);
          //  MessageBox.Show(signedXml.Signature.SignedInfo.CanonicalizationMethod);
            return signedXml.CheckSignature();
        }

        

       

        private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            string s=saveFileDialog1.FileName;
            using (FileStream fs = new FileStream(s, FileMode.OpenOrCreate))
            {
                x.Save(s + ".1.xml");
                using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
                {
                    w.Write(signatur);
                    w.Close();
                }
            }
            setfilename(s);

        }

        private void webClient1_DownloadDataCompleted(object sender, System.Net.DownloadDataCompletedEventArgs e)
        {

        }

        
    }
}
